<template>
  <component :is="iconComponent" v-if="iconComponent" :style="iconStyle" />
  <AppstoreOutlined v-else :style="iconStyle" />
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { AppstoreOutlined } from '@ant-design/icons-vue'

interface Props {
  name?: string
  size?: string | number
}

const props = withDefaults(defineProps<Props>(), {
  name: '',
  size: 'default',
})

// 动态图标组件
const iconComponent = ref<any>(null)

// 图标缓存，避免重复导入
const iconCache = new Map<string, any>()

// 动态导入图标
const loadIcon = async (iconName: string) => {
  if (!iconName || iconName === 'NULL' || iconName.toLowerCase() === 'null') {
    iconComponent.value = null
    return
  }

  // 检查缓存
  if (iconCache.has(iconName)) {
    iconComponent.value = iconCache.get(iconName)
    return
  }

  try {
    // 动态导入图标
    const iconModule = (await import('@ant-design/icons-vue')) as any

    // 检查图标是否存在
    if (iconModule[iconName]) {
      const icon = iconModule[iconName]
      iconCache.set(iconName, icon) // 缓存图标
      iconComponent.value = icon
    } else {
      console.warn(`图标 ${iconName} 不存在，使用默认图标`)
      iconComponent.value = null
      iconCache.set(iconName, null) // 缓存空值，避免重复尝试
    }
  } catch (error) {
    console.error(`加载图标 ${iconName} 失败:`, error)
    iconComponent.value = null
    iconCache.set(iconName, null)
  }
}

// 监听图标名称变化
watch(
  () => props.name,
  (newName) => {
    if (newName) {
      loadIcon(newName)
    } else {
      iconComponent.value = null
    }
  },
  { immediate: true }
)

// 样式计算
const iconStyle = computed(() => {
  const style: any = {}

  if (props.size !== 'default') {
    if (typeof props.size === 'number') {
      style.fontSize = `${props.size}px`
    } else {
      style.fontSize = props.size
    }
  }

  return style
})
</script>

<style scoped>
.dynamic-icon {
  display: inline-flex;
  align-items: center;
}
</style> 